package com.sangmo.fts.basic.service;

import com.sangmo.boot.framework.common.utils.UuidUtils;
import com.sangmo.boot.framework.data.filter.PageResult;
import com.sangmo.boot.framework.data.filter.PageSearch;
import com.sangmo.fts.basic.model.FileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
@Transactional
public class FileUploadService {

    @Autowired
    private FileUploadEntityService fileUploadEntityService;

    @Value("${upload.filePath}")
    private String uploadFilePath;

    public FileUpload find(Long id) {
        return fileUploadEntityService.find(id);
    }

    public PageResult<FileUpload> search(PageSearch ps) {
        return fileUploadEntityService.search(ps);
    }

    public FileUpload updateRef(Long id, String refNo, String refType) {
        FileUpload fileUpload = fileUploadEntityService.get(id);
        fileUpload.setRefNo(refNo);
        fileUpload.setRefType(refType);
        return fileUploadEntityService.save(fileUpload);
    }

    public void remove(Long id) {
        fileUploadEntityService.deleteById(id);
    }

    public FileUpload uploadFile(MultipartFile file, HttpServletRequest request) throws Exception {
        FileUpload fileUpload = new FileUpload();
        fileUpload.setFileName(file.getOriginalFilename());
        fileUpload.setSize(file.getSize());
        //获取绝对路径
        String realPath=uploadFilePath;
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd/");
        String format=sdf.format(new Date());
        //文件存放的目录
        File folder=new File(realPath+format);
        if(!folder.isDirectory()){
            folder.mkdirs();
        }
        String oldName=file.getOriginalFilename();
        //文件后缀
        String suffix=oldName.substring(oldName.lastIndexOf("."),oldName.length());
        //文件新名字
        String newName=UuidUtils.getUUID()+suffix;

        File targetFile=new File(folder,newName);

        if(!targetFile.exists()){
            targetFile.mkdirs();
        }else {
            targetFile.delete();
        }
        file.transferTo(targetFile);
        String filePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/uploadFile/"+format+newName;

        fileUpload.setUrl(filePath);
        fileUpload = fileUploadEntityService.save(fileUpload);
        return fileUpload;
    }


    public FileUpload upload(MultipartFile file) throws IOException {
        FileUpload fileUpload = new FileUpload();
        fileUpload.setFileName(file.getOriginalFilename());
        fileUpload.setSize(file.getSize());

        String sysTempPath = System.getProperty("user.dir");
//        String path = ResourceUtils.getURL("classpath:").getPath() + "static/files/";
        String fileDir = sysTempPath + makeDir();

        String fileSuffix = this.getFileSuffix(file);
        String fileName = UuidUtils.getUUID() + "." + fileSuffix;

        String outputPath = fileDir + fileName;

        this.mkDir(fileDir);

        File tempFile = new File(outputPath);
        file.transferTo(tempFile);

//        String uri = makeName(file.getOriginalFilename());
//        String fileUrl = path + uri;
//
//        this.upload(tempFile, uri);
//        this.deleteFile(tempFile);

        fileUpload.setUrl(outputPath);
        fileUpload = fileUploadEntityService.save(fileUpload);
        return fileUpload;
    }

    private String makeName(String fileName) {
        SimpleDateFormat format = new SimpleDateFormat("/yyyy/MM/");
        String name = "fts" + format.format(new Date()) + UuidUtils.getUUID();
        if (!StringUtils.isEmpty(fileName)) {
            String ext = FilenameUtils.getExtension(fileName);
            if (!StringUtils.isEmpty(ext)) {
                name = name + "." + FilenameUtils.getExtension(fileName);
            }
        }
        return name;
    }

    private String makeDir() {
        SimpleDateFormat format = new SimpleDateFormat("/yyyy/MM/");
        String dir = "/files" + format.format(new Date());
        return dir;
    }

    private void mkDir(String dir) {
        File myFolderPath = new File(dir);
        try {
            if (!myFolderPath.exists()) {
                System.out.println(myFolderPath.mkdir());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getFileSuffix(MultipartFile file) {
        String suffix = null;
        if (null != file) {
            String name = file.getOriginalFilename();
            suffix = name.substring(name.lastIndexOf(".") + 1);
        }
        return suffix;
    }

    private void deleteFile(File file) {
        if (file.exists()) {
            file.delete();
        }
    }
}
